package com.example.understandvideo.tool;

import org.apache.commons.lang3.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.util.concurrent.TimeUnit.*;

public class DateFormatUtil {
    public static String DatetimeToString(Date date) {
        if (date != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return sdf.format(date);
        }
        return "";
    }

    public static String DatetimeToYear(Date date) {
        if (date != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
            return sdf.format(date);
        }
        return "";
    }

    public static String DateToString(Date date) {
        if (date != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            return sdf.format(date);
        }
        return "";
    }

    public static String DateToStringV2(Date date) {
        if (date != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            return sdf.format(date);
        }
        return "";
    }

    public static Date StringToDatetime(String dateString) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return sdf.parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static Date StringToDate(String dateString) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            return sdf.parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Date StringToDateIngest(String dateString) {
        try {
            Calendar calendar = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            calendar.setTime(sdf.parse(dateString));
            return calendar.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Date StringToDateEnd(String dateString) {
        try {
            Calendar calendar = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            calendar.setTime(sdf.parse(dateString));
            calendar.add(Calendar.SECOND, 86399);
            return calendar.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String timeToString(long time) {
        Date date = new Date();
        date.setTime(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date);
    }

    public static String millsecondsToString(long duration) {
        final TimeUnit scale = MILLISECONDS;

        long days = scale.toDays(duration);
        duration -= DAYS.toMillis(days);
        long hours = scale.toHours(duration);
        duration -= HOURS.toMillis(hours);
        long minutes = scale.toMinutes(duration);
        duration -= MINUTES.toMillis(minutes);
        long seconds = scale.toSeconds(duration);
        duration -= SECONDS.toMillis(seconds);
        long millis = scale.toMillis(duration);
        duration -= MILLISECONDS.toMillis(seconds);
        long nanos = scale.toNanos(duration);

        String hour = hours < 10 ? "0".concat(String.valueOf(hours)) : String.valueOf(hours);
        String minute = minutes < 10 ? "0".concat(String.valueOf(minutes)) : String.valueOf(minutes);
        String second = seconds < 10 ? "0".concat(String.valueOf(seconds)) : String.valueOf(seconds);

        return String.format("%s:%s:%s", hour, minute, second);

    }

    /**
     * 将毫秒转为几分几秒
     */
    public static String millsecondsFormat(Long ms) {
        if (ms < 1000) {
            return "1秒";
        }
        String result = "";
        long seconds = ms / 1000;
        long minutesStr = seconds / 60;
        long secondsStr = seconds % 60;
        if (minutesStr > 0) {
            result += minutesStr + " 分钟 ";
        }
        if (secondsStr > 0) {
            result += secondsStr + " 秒";
        }
        return result;
    }

    public static String formatDateToHHmmss(Long duration, boolean showFrame) {
        if (duration == null) {
            return "";
        }
        long ms = duration % 1000;
        long second = duration / 1000;
        long minute = second / 60;
        long hour = minute / 60;
        second %= 60;
        minute %= 60;

        StringBuilder sb = new StringBuilder();

        sb.append(StringUtils.leftPad(String.valueOf(hour), 2, '0')).append(":")
                .append(StringUtils.leftPad(String.valueOf(minute), 2, '0')).append(":")
                .append(StringUtils.leftPad(String.valueOf(second), 2, '0')).append(".");
        if (showFrame) {
            sb.append(StringUtils.leftPad(String.valueOf(ms / 40), 2, '0'));
        } else {
            sb.append(StringUtils.leftPad(String.valueOf(ms), 3, '0'));
        }

        return sb.toString();
    }

    public static String formatDateToHHmmssV2(Long duration, boolean showFrame) {
        if (duration == null) {
            return "";
        }
        long ms = duration % 1000;
        long second = duration / 1000;
        long minute = second / 60;
        long hour = minute / 60;
        second %= 60;
        minute %= 60;

        StringBuilder sb = new StringBuilder();

        sb.append(StringUtils.leftPad(String.valueOf(hour), 2, '0')).append(":")
                .append(StringUtils.leftPad(String.valueOf(minute), 2, '0')).append(":")
                .append(StringUtils.leftPad(String.valueOf(second), 2, '0')).append(":");
        if (showFrame) {
            sb.append(StringUtils.leftPad(String.valueOf(ms / 40), 2, '0'));
        } else {
            sb.append(StringUtils.leftPad(String.valueOf(ms), 3, '0'));
        }

        return sb.toString();
    }

    public static Long convertToMil(String time) {
        if (StringUtils.isEmpty(time)) {
            return 0L;
        }

        long duration = 0;
        String[] tmpArray = time.split("\\.");
        String hhmmss = time;
        if (tmpArray.length == 2) {
            duration += Long.parseLong(tmpArray[1]);
            hhmmss = tmpArray[0];
        }

        String[] hhmmssArray = hhmmss.split(":");
        duration += (Long.parseLong(hhmmssArray[0]) * 3600 + Long.parseLong(hhmmssArray[1]) * 60 + Long.parseLong(hhmmssArray[2])) * 1000;
        return duration;
    }

    /**
     * 将毫秒转为几时
     */
    public static String millsecondsFormatHour(Long ms) {
        if (ms < 3600000) {
            return millsecondsFormat(ms);
        }
        String result = "";
        long seconds = ms / 1000;
        long minutesStr = seconds / 60;
        long hour = minutesStr / 60;
        if (hour > 0) {
            result += hour + " 小时 ";
        }
        return result;
    }

    /**
     * 根据传入的值返回时分秒毫秒信息
     */
    public static String millSecondsFormatInput(Long time, String format) {
        // 解析传入字符
        Pattern pattern = Pattern.compile("S");
        Matcher matcher = pattern.matcher(format);
        int msCount = 0;
        while (matcher.find()) {
            msCount++;
        }

        if (time == null) {
            String defaultValue = "00:00:00";
            if (msCount > 0) {
                defaultValue = defaultValue + ".";
                for (int i = 0; i < msCount; i++) {
                    defaultValue = defaultValue + "0";
                }
            }
            return defaultValue;
        }


        long ms = time % 1000;
        long second = time / 1000;
        long minute = second / 60;
        long hour = minute / 60;
        second %= 60;
        minute %= 60;

        StringBuilder sb = new StringBuilder();

        sb.append(StringUtils.leftPad(String.valueOf(hour), 2, '0')).append(":")
                .append(StringUtils.leftPad(String.valueOf(minute), 2, '0')).append(":")
                .append(StringUtils.leftPad(String.valueOf(second), 2, '0'));
        if (msCount > 0 && ms > 0) {
            sb.append(".").append(
                    StringUtils.left(
                            StringUtils.leftPad(String.valueOf(ms), 3, '0')
                            , msCount
                    )
            );
        }

        return sb.toString();
    }
}
